<?php
declare (strict_types=1);

namespace wechat;

use EasyWeChat\Factory;

/**
 * 取袋微信小程序
 */
class ScanBagMiniProgram
{
    //微信小程序
    public object $app;
    //小程序原始id
    public string $username;
    public string $appid;
    public string $secret;
    //微信小程序广告ID
    public array $advert;

    /**
     * 初始化
     * @param array $mini
     */
    public function __construct(array $mini)
    {
        //获取对应的配置
        $this->appid = $mini['mini_appid'];
        $this->secret = $mini['mini_secret'];
        $this->username = $mini['mini_username'];
        //微信小程序广告ID
        $this->advert = json_decode($mini['mini_advert'], true);
        //app
        $config = [
            'app_id' => $this->appid,
            'secret' => $this->secret,
            'response_type' => 'array',
        ];
        $this->app = Factory::miniProgram($config);
    }

    /**
     * 微信小程序通过code获取用户信息
     * @param string $code
     * @return array
     */
    public function userFromCode(string $code): array
    {
        return $this->app->auth->session($code);
    }

    /**
     * 微信小程序URLScheme
     * @param string $path
     * @param string $query
     * @param int $expire_time
     * @return array
     */
    public function URLScheme(string $path, string $query, int $expire_time = 3600): array
    {
        $arr = [
            'is_expire' => true,
            'expire_time' => time() + $expire_time,
            'jump_wxa' => [
                'path' => $path,
                'query' => $query,
                'env_version' => 'release',
            ]
        ];
        $res = $this->app->url_scheme->generate($arr);
        if ($res['errcode'] == 0) {
            return ['bool' => true, 'openlink' => $res['openlink'], 'msg' => $res['errmsg'], 'username' => $this->username];
        }
        return ['bool' => false, 'openlink' => '', 'msg' => $res['errmsg'], 'username' => $this->username];
    }


}















